import pytest
import requests
from unittest.mock import patch, MagicMock

# 测试配置
TEST_REGION = "ap-guangzhou"
TEST_ACTION = "DescribeInstanceTypeConfigs"
TEST_VERSION = "2017-03-12"


# 模拟认证头生成函数（需根据实际情况实现）
def generate_auth_headers(secret_id, secret_key):
    return {
        "Authorization": "TC3-HMAC-SHA256 Credential=...",
        "Content-Type": "application/json",
        "X-TC-Action": TEST_ACTION,
        "X-TC-Version": TEST_VERSION,
        "X-TC-Timestamp": "1710230358",
        "X-TC-Nonce": "123456789"
    }


# 测试类
class TestDescribeInstanceTypeConfigs:

    @pytest.fixture(scope="session")
    def auth_headers(self):
        return generate_auth_headers("test_secret_id", "test_secret_key")

    def test_normal_case(self, auth_headers, mocker):
        """测试正常查询"""
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            "Response": {
                "InstanceTypeConfigSet": [
                    {
                        "Zone": "ap-guangzhou-2",
                        "InstanceFamily": "I1",
                        "InstanceType": "I1.MEDIUM4",
                        "CPU": 2,
                        "Memory": 8,
                        "GPU": 0,
                        "FPGA": 0
                    },
                    {
                        "Zone": "ap-guangzhou-2",
                        "InstanceFamily": "S1",
                        "InstanceType": "S1.SMALL1",
                        "CPU": 2,
                        "Memory": 8,
                        "GPU": 0,
                        "FPGA": 0
                    }
                ],
                "TotalCount": 2,
                "RequestId": "mock-request-id"
            }
        }
        mocker.patch('requests.post', return_value=mock_response)

        response = requests.post(
            f"https://{TEST_REGION}.cvm.tencentcloudapi.com",
            headers=auth_headers,
            params={
                "Action": TEST_ACTION,
                "Version": TEST_VERSION,
                "Region": TEST_REGION
            }
        )

        assert response.status_code == 200
        assert len(response.json()["Response"]["InstanceTypeConfigSet"]) == 2

    def test_missing_region(self, mocker, auth_headers):
        """测试缺少Region参数"""
        mock_response = MagicMock()
        mock_response.status_code = 400
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidParameterValue.RegionMissing",
                    "Message": "Region parameter is required"
                }
            }
        }
        mocker.patch('requests.post', return_value=mock_response)

        # 显式触发异常检查
        response = requests.post(
            "https://cvm.tencentcloudapi.com",
            headers=auth_headers,
            params={
                "Action": TEST_ACTION,
                "Version": TEST_VERSION
            }
        )
        response.raise_for_status()  # 这里会触发HTTPError

    def test_invalid_action(self, mocker, auth_headers):
        """测试无效Action参数"""
        mock_response = MagicMock()
        mock_response.status_code = 400
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidAction",
                    "Message": "The action is invalid"
                }
            }
        }
        mocker.patch('requests.post', return_value=mock_response)

        response = requests.post(
            f"https://{TEST_REGION}.cvm.tencentcloudapi.com",
            headers=auth_headers,
            params={
                "Action": "InvalidAction",
                "Version": TEST_VERSION,
                "Region": TEST_REGION
            }
        )
        response.raise_for_status()  # 显式触发异常

    def test_invalid_version(self, mocker, auth_headers):
        """测试无效Version参数"""
        mock_response = MagicMock()
        mock_response.status_code = 400
        mock_response.json.return_value = {
            "Response": {
                "Error": {
                    "Code": "InvalidVersion",
                    "Message": "Version mismatch"
                }
            }
        }
        mocker.patch('requests.post', return_value=mock_response)

        response = requests.post(
            f"https://{TEST_REGION}.cvm.tencentcloudapi.com",
            headers=auth_headers,
            params={
                "Action": TEST_ACTION,
                "Version": "invalid-version",
                "Region": TEST_REGION
            }
        )
        response.raise_for_status()  # 显式触发异常

    def test_network_failure(self, mocker):
        """测试网络错误"""
        mocker.patch('requests.post', side_effect=requests.exceptions.ConnectionError)

        with pytest.raises(requests.exceptions.ConnectionError):
            requests.post(
                f"https://{TEST_REGION}.cvm.tencentcloudapi.com",
                headers={},
                params={}
            )


# 运行配置
if __name__ == "__main__":
    pytest.main([
        __file__,
        "-s",  # 显示详细输出
        "--html=report.html",  # 生成HTML报告
        "--self-contained-html",  # 将CSS嵌入HTML
        "--cov=.",  # 代码覆盖率分析
        "--cov-report=term-missing"  # 显示未覆盖代码
    ])